<template>
  <el-dialog
    v-model="visible"
    title="多车辆对比分析"
    width="1200px"
    @close="handleClose"
  >
    <div class="space-y-6">
      <!-- 车辆选择 -->
      <div class="bg-gray-50 p-4 rounded-lg">
        <h3 class="text-sm font-medium text-gray-900 mb-3">选择对比车辆（2-4辆）</h3>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-2">
          <div 
            v-for="vehicle in availableVehicles" 
            :key="vehicle.id"
            class="flex items-center"
          >
            <el-checkbox 
              v-model="selectedVehicleIds"
              :label="vehicle.id"
              :disabled="!canSelectMore && !selectedVehicleIds.includes(vehicle.id)"
            >
              <span class="text-sm">{{ vehicle.id }}</span>
            </el-checkbox>
          </div>
        </div>
      </div>

      <!-- 对比内容 -->
      <div v-if="selectedVehicles.length >= 2" class="space-y-6">
        <!-- 热工况向量对比 -->
        <div class="bg-white border rounded-lg p-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">热工况向量对比</h3>
          <div class="h-64">
            <v-chart :option="thmCompareOption" class="w-full h-full" />
          </div>
        </div>

        <!-- 风险指标对比 -->
        <div class="bg-white border rounded-lg p-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">风险指标对比</h3>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="h-64">
              <v-chart :option="ctiCompareOption" class="w-full h-full" />
            </div>
            <div class="h-64">
              <v-chart :option="socJumpCompareOption" class="w-full h-full" />
            </div>
          </div>
        </div>

        <!-- 详细对比表格 -->
        <div class="bg-white border rounded-lg p-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">详细参数对比</h3>
          <el-table :data="comparisonData" style="width: 100%">
            <el-table-column prop="parameter" label="参数" width="120" />
            <el-table-column 
              v-for="vehicle in selectedVehicles" 
              :key="vehicle.id"
              :prop="vehicle.id" 
              :label="vehicle.id"
              width="150"
            >
              <template #default="{ row }">
                <span :class="getComparisonColor(row, vehicle.id)">
                  {{ row[vehicle.id] }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 差异分析 -->
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <h3 class="text-lg font-semibold text-blue-900 mb-3">差异分析</h3>
          <div class="space-y-2">
            <div v-for="analysis in differenceAnalysis" :key="analysis.type" class="text-sm">
              <span class="font-medium text-blue-800">{{ analysis.type }}：</span>
              <span class="text-blue-700">{{ analysis.description }}</span>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="text-center text-gray-500 py-8">
        请选择至少2辆车辆进行对比分析
      </div>
    </div>
    
    <template #footer>
      <div class="flex justify-end space-x-2">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="exportComparison">导出对比报告</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useAppStore } from '@/stores'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, RadarChart } from 'echarts/charts'
import { 
  GridComponent, 
  TooltipComponent, 
  LegendComponent,
  RadarComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { ElMessage } from 'element-plus'

use([
  CanvasRenderer,
  BarChart,
  RadarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  RadarComponent
])

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const store = useAppStore()

const visible = ref(false)
const selectedVehicleIds = ref<string[]>([])

const availableVehicles = computed(() => store.vehicles)
const selectedVehicles = computed(() => 
  store.vehicles.filter(v => selectedVehicleIds.value.includes(v.id))
)
const canSelectMore = computed(() => selectedVehicleIds.value.length < 4)

watch(() => props.modelValue, (val) => {
  visible.value = val
})

const thmCompareOption = computed(() => ({
  title: {
    text: '热工况向量对比',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: selectedVehicles.value.map(v => v.id),
    bottom: 0
  },
  xAxis: {
    type: 'category',
    data: ['温度归一化', '放电时长归一化', '功率归一化']
  },
  yAxis: {
    type: 'value',
    min: 0,
    max: 1
  },
  series: selectedVehicles.value.map((vehicle, index) => ({
    name: vehicle.id,
    type: 'bar',
    data: vehicle.thmVector,
    itemStyle: {
      color: ['#3b82f6', '#ef4444', '#22c55e', '#f59e0b'][index]
    }
  }))
}))

const ctiCompareOption = computed(() => ({
  title: {
    text: 'CTI 值对比',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: selectedVehicles.value.map(v => v.id)
  },
  yAxis: {
    type: 'value',
    name: 'CTI 值'
  },
  series: [{
    type: 'bar',
    data: selectedVehicles.value.map(vehicle => ({
      value: store.calculateCTI(vehicle.thmVector),
      itemStyle: {
        color: vehicle.riskLevel === 'high' ? '#ef4444' : 
              vehicle.riskLevel === 'warning' ? '#f59e0b' : '#22c55e'
      }
    }))
  }]
}))

const socJumpCompareOption = computed(() => ({
  title: {
    text: 'SOC 跳变幅度对比',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: selectedVehicles.value.map(v => v.id)
  },
  yAxis: {
    type: 'value',
    name: '跳变幅度 (%)'
  },
  series: [{
    type: 'bar',
    data: selectedVehicles.value.map(() => Math.random() * 5 + 1), // 模拟数据
    itemStyle: {
      color: '#f59e0b'
    }
  }]
}))

const comparisonData = computed(() => [
  {
    parameter: 'SOC (%)',
    ...Object.fromEntries(selectedVehicles.value.map(v => [v.id, v.soc + '%']))
  },
  {
    parameter: '温度 (℃)',
    ...Object.fromEntries(selectedVehicles.value.map(v => [v.id, v.temperature + '℃']))
  },
  {
    parameter: '放电时长 (min)',
    ...Object.fromEntries(selectedVehicles.value.map(v => [v.id, v.dischargeTime + 'min']))
  },
  {
    parameter: '最大功率 (kW)',
    ...Object.fromEntries(selectedVehicles.value.map(v => [v.id, v.maxPower + 'kW']))
  },
  {
    parameter: 'CTI 值',
    ...Object.fromEntries(selectedVehicles.value.map(v => [v.id, store.calculateCTI(v.thmVector).toFixed(3)]))
  },
  {
    parameter: '风险等级',
    ...Object.fromEntries(selectedVehicles.value.map(v => [v.id, 
      v.riskLevel === 'high' ? '高风险' : 
      v.riskLevel === 'warning' ? '风险预警' : '低风险'
    ]))
  }
])

const differenceAnalysis = computed(() => {
  if (selectedVehicles.value.length < 2) return []
  
  const analyses = []
  
  // CTI 差异分析
  const ctiValues = selectedVehicles.value.map(v => ({
    id: v.id,
    cti: store.calculateCTI(v.thmVector)
  })).sort((a, b) => a.cti - b.cti)
  
  analyses.push({
    type: 'CTI 差异',
    description: `${ctiValues[0].id} CTI(${ctiValues[0].cti.toFixed(3)}) < ${ctiValues[ctiValues.length-1].id} CTI(${ctiValues[ctiValues.length-1].cti.toFixed(3)})`
  })
  
  // SOC 差异分析
  const socValues = selectedVehicles.value.map(v => ({
    id: v.id,
    soc: v.soc
  })).sort((a, b) => a.soc - b.soc)
  
  analyses.push({
    type: 'SOC 差异',
    description: `${socValues[0].id} SOC(${socValues[0].soc}%) < ${socValues[socValues.length-1].id} SOC(${socValues[socValues.length-1].soc}%)`
  })
  
  return analyses
})

const getComparisonColor = (row: any, vehicleId: string) => {
  if (row.parameter === '风险等级') {
    const value = row[vehicleId]
    if (value === '高风险') return 'text-red-600'
    if (value === '风险预警') return 'text-yellow-600'
    return 'text-green-600'
  }
  return 'text-gray-900'
}

const handleClose = () => {
  visible.value = false
  emit('update:modelValue', false)
}

const exportComparison = () => {
  const data = {
    vehicles: selectedVehicles.value.map(v => ({
      id: v.id,
      model: v.model,
      soc: v.soc,
      temperature: v.temperature,
      thmVector: v.thmVector,
      cti: store.calculateCTI(v.thmVector),
      riskLevel: v.riskLevel
    })),
    timestamp: new Date().toISOString()
  }
  
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `vehicle_comparison_${new Date().toISOString().slice(0, 10)}.json`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('对比报告已导出')
}
</script>